<template>
	<view class="content">
		<form class="sub-form" @submit="submit" enctype="multipart/form-data">
			<view class="form-item type">
				<view class="title type">
					搭子类型
				</view>
				<uni-data-select class="select-item" v-model="value" :localdata="typeList" :clear="false"
					@change="change" />
			</view>
			<view class="form-item">
				<view class="title text">
					标题
				</view>
				<input v-model="title" placeholder="请输入标题" placeholder-class="input-placeholder" maxlength="16" />
			</view>
			<view class="form-item">
				<view class="title text">
					内容
				</view>
				<textarea name="" id="" v-model="content" placeholder="请输入内容" style="width: 85vw;" maxlength="100"
					@input="checkLength" />
				<view class="counter">{{ remainingCount }}/100</view>
			</view>
			<view class="form-item">
				<view class="title">
					上传图片(选填)
				</view>
				<uni-file-picker 
					v-model="tempFiles" 
					:limit="uploadImgLimit" 
					:title="`最多${uploadImgLimit}张图`"
					file-mediatype="image" 
					:auto-upload="false" 
					@select="select" 
					@delete="deleteFile"
					/>
			</view>
			<view class="form-item submit">
				<button type="default" form-type="submit">立即发布</button>
			</view>
		</form>
	</view>
</template>

<script>
	import {
		showToast,
		navigateBack,
		uploadFile
	} from '../../utils/promise'
	import {
		bbsCreate,
		bbsUpdate,
		mybbsList
	} from '../../api/bbs'
	import {
		BASE_URL
	} from '../../utils/request'
	export default {
		data() {
			return {
				value: 0,
				typeList: [{
						value: 0,
						text: "周边游"
					},
					{
						value: 1,
						text: "本地美食"
					},
					{
						value: 2,
						text: "景区景点"
					},
					{
						value: 3,
						text: "娱乐活动"
					},
				],
				title: "",
				content: "",
				bbsId: 0,
				uploadImgLimit: 4,
				tempFiles: [],
				maxLength: 100,
				remoteUrls: []
			}
		},
		onLoad(options) {
			if (options.id) {
				this.bbsId = options.id
				this.getbbsById()
			}
		},
		computed: {
			remainingCount() {
				return this.maxLength - this.content.length
			}
		},
		methods: {
			select(e) {
				this.tempFiles.push(...e.tempFiles)
				this.upLoadImgs()
			},
			deleteFile(e) {
				const index = this.tempFiles.findIndex(file => file.url === e.tempFile.url)
        console.log("deleteFile.index", index)
				if (index !== -1) {
					this.remoteUrls.splice(index, 1)
				}
			},
			checkLength() {
				if (this.content.length > this.maxLength) {
					this.content = this.content.substring(0, this.maxLength)
				}
			},
			submit() {
				if (!this.typeList[this.value].text) {
					showToast({
						title: '请选择搭子类型',
						mask: true
					})
					return
				}
				if (!this.title) {
					showToast({
						title: "请填写标题",
						icon: "error",
						mask: true
					})
					return
				}
				if (!this.content) {
					showToast({
						title: "请填写内容"
					})
					return
				}
				if (this.bbsId) {
					this.editbbs()
					return
				}
				this.createbbs()
			},
			getbbsById() {
				mybbsList().then((res) => {
					const {
						code,
						data,
						msg
					} = res
					if (code === 200) {
						const bbsInfo = data.records.find((item) => item.id == this.bbsId)
						this.title = bbsInfo.title
						this.content = bbsInfo.content
						this.value = bbsInfo.type
						this.remoteUrls = [...bbsInfo.coverList]
						this.tempFiles = bbsInfo.coverList.map((item, idx) => {
							return {
								name: item,
								url: item,
								extname: getImageExtensionFromUrl(item)
							}
						})
					}
				}).catch((err) => {
					console.log(err)
				})

				function getImageExtensionFromUrl(urlString) {
					if (!urlString || typeof urlString !== 'string') {
						return '';
					}
					try {
						// 使用 URL 对象解析路径名，可以处理查询参数和哈希
						const url = new URL(urlString);
						const pathname = url.pathname;

						// 查找最后一个 '.' 的位置
						const lastDotIndex = pathname.lastIndexOf('.');

						// 确保找到了 '.' 并且它不是路径的最后一个字符
						if (lastDotIndex > -1 && lastDotIndex < pathname.length - 1) {
							return pathname.substring(lastDotIndex + 1);
						}
					} catch (e) {
						// 如果 URL 无效，尝试直接从字符串处理
						const lastDotIndex = urlString.lastIndexOf('.');
						// 移除查询参数和哈希值的影响
						const questionMarkIndex = urlString.indexOf('?');
						const hashIndex = urlString.indexOf('#');
						let pathEndIndex = urlString.length;
						if (questionMarkIndex !== -1) {
							pathEndIndex = questionMarkIndex;
						}
						if (hashIndex !== -1 && hashIndex < pathEndIndex) {
							pathEndIndex = hashIndex;
						}

						if (lastDotIndex > -1 && lastDotIndex < pathEndIndex - 1) {
							// 确保点在有效路径部分
							const potentialExtension = urlString.substring(lastDotIndex + 1, pathEndIndex);
							// 避免路径片段被误认为是后缀
							if (!potentialExtension.includes('/')) {
								return potentialExtension;
							}
						}
					}

					return ''; // 没有找到有效的后缀名
				}
			},
			async upLoadImgs() {
				if (!this.tempFiles.length) {
					return
				}
				const header = {
					"Authorization": `Bearer ${uni.getStorageSync("userToken")}`,
					'X-Client-Type': 'MINI_PROGRAM',
				}
				try {
					uni.showLoading({
						title: '上传中...'
					})
          const uploadResList = await Promise.all(this.tempFiles.map((tempFile, index) => {
						const notUpload = index >= this.remoteUrls.length
						if (notUpload) {
							return uploadFile({
								url: `${BASE_URL}/api/file/upload`,
								filePath: tempFile.path,
								header: header,
								name: "file",
								formData: {
									'fileClassification': 'COMMENT',
								},
							})
						} else {
							return Promise.resolve(false)
						}
					}))
					uploadResList.forEach((res, idx) => {
						if (res !== false) {
							const {
								code,
								data,
								msg
							} = JSON.parse(res.data)
							if (code === 200) {
								this.remoteUrls[idx] = data
							} else {
								throw new Error(msg)
							}
						}
					})
					uni.hideLoading()
				} catch (error) {
					uni.hideLoading()
					this.tempFiles = []
					this.remoteUrls = []
					console.log(error)
					showToast({
						title: '上传失败'
					})
				}
			},

			editbbs() {
				const coverList = this.remoteUrls
				let params = {
					id: this.bbsId,
					type: this.typeList[this.value].value,
					title: this.title,
					content: this.content,
					coverList,
					status: 1
				}
				bbsUpdate(params).then((res) => {
					if (res.code !== 200 || !res.data) {
						showToast({
							title: res.msg
						})
						return
					}
					showToast({
						title: "发布成功"
					}).then(() => {
						navigateBack()
					})

				}).catch((err) => {
					console.log(err)
				})
			},
			createbbs() {
				const coverList = this.remoteUrls
				let params = {
					type: this.typeList[this.value].value,
					title: this.title,
					content: this.content,
					coverList
				}
				bbsCreate(params).then((res) => {
					const {
						code,
						data,
						msg
					} = res
					if (code !== 200 || !data) {
						showToast({
							title: msg
						})
						return
					}
					showToast({
						title: "发布成功"
					}).then(() => {
						navigateBack()
					})
				}).catch((err) => {
					console.log(err)
				})
			}
		}
	}
</script>

<style scoped>
	.content {
		margin: 0 auto;
		width: 100vw;
		min-height: 100vh;
		background-color: #f7f7f7;
	}

	.sub-form {
		padding-top: 25rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.form-item {
		width: 90vw;
		padding: 15rpx;
		margin: 50rpx 0;
		display: flex;
		flex-direction: column;
		background-color: rgb(255, 255, 255);
		border-radius: 15rpx;
		font-size: 26rpx;
	}

	.form-item:first-child {
		margin-top: 0;
	}

	.form-item.type {
		display: grid;
		grid-template-columns: 5rem 1fr;
	}

	.submit {
		background-color: transparent;
		padding: 0;
		width: 90%;
		position: absolute;
		bottom: 36rpx;
		left: 50%;
		transform: translateX(-50%);
		place-content: center;
		place-items: center;
	}

	.submit button {
		background-color: rgb(15, 76, 151);
		color: white;
		border-radius: 60rpx;
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
	}

	.select-item {
		background-color: transparent;
	}

	.title {
		font-weight: bold;
		padding-left: 10rpx;
		display: flex;
		align-items: center;
		font-size: 26rpx;
	}

	.form-item input,
	.form-item textarea {
		padding: 20rpx;
		border-bottom: 2rpx solid #e5e5e5;
	}

	.form-item textarea {
		height: 5rem;
	}

	::v-deep .file-title {
		text-indent: 2rem;
	}

	::v-deep .icon-add {
		background-color: rgb(119, 119, 119) !important;
	}

	::v-deep .is-add {
		border-color: rgb(121, 121, 121) !important;
	}
</style>